# _*_ coding:utf8 _*_

import cv2
import flask
from flask import request
import base64
import uuid
import json
from digit_calculate import get_char_list, calculate_digit


'''
flask： web框架，通过flask提供的装饰器@server.route()将普通函数转换为服务
登录接口，需要传url、username、passwd
'''

# 创建一个服务，把当前这个python文件当做一个服务
server = flask.Flask(__name__)


@server.route('/digit/recognition/post', methods=['post'])
def post_digit_recognition():
    if not request.data:
        # 检测是否有数据
        return "fail"
    # 取值
    request_data = request.data.decode('utf-8')
    data_json = json.loads(request_data)
    # 从json中获取数据
    base64_string = data_json["imageBase64"]
    # 获取参数，其实是避免get方法的参数在http传输中会替换
    base64_string_change = base64_string.replace(" ", "+")

    # 根据逗号切分出base64字符串
    comma_index = base64_string_change.find(",")
    if comma_index >= 0:
        base64_code = base64_string_change[comma_index+1:]
    else:
        base64_code = base64_string_change

    # 解码
    base64_image = base64.b64decode(base64_code)

    # 保存图片
    uuid_string = uuid.uuid1()
    image_path = './request_image/' + str(uuid_string) + '.png'

    # 用写文件的方式写入
    image_file = open(image_path, 'wb')
    image_file.write(base64_image)
    image_file.close()

    # 读取图片
    image_data = cv2.imread(image_path)

    char_list = get_char_list(image_data)
    recognition_result = calculate_digit(char_list)
    print(image_path, recognition_result)

    json_result = {'code': 200, 'result': recognition_result}

    # 将字典转换为json串，json字符串
    return json.dumps(json_result, ensure_ascii=False)


@server.route('/digit/recognition/get', methods=['get'])
def get_digit_recognition():
    # 获取参数
    base64_string = request.args.get('imageBase64')
    # 避免get方法的参数在http传输中会替换
    base64_string_change = base64_string.replace(" ", "+")

    # 根据逗号切分出base64字符串
    comma_index = base64_string_change.find(",")
    if comma_index >= 0:
        base64_code = base64_string_change[comma_index+1:]
    else:
        base64_code = base64_string_change

    # 解码
    base64_image = base64.b64decode(base64_code)
    # 保存图片
    uuid_string = uuid.uuid1()
    image_path = './request_image/' + str(uuid_string) + '.png'

    # 用写文件的方式写入
    image_file = open(image_path, 'wb')
    image_file.write(base64_image)
    image_file.close()

    # 读取图片
    image_data = cv2.imread(image_path)

    char_list = get_char_list(image_data)
    recognition_result = calculate_digit(char_list)
    print(image_path, recognition_result)

    json_result = {'code': 200, 'result': recognition_result}

    # 将字典转换为json串，json字符串
    return json.dumps(json_result, ensure_ascii=False)


if __name__ == '__main__':
    # 启动接口
    server.run(debug=True, port=8082, host='0.0.0.0')
